<?php



/**
 * 工具类,提供字符串处理,数字运算等方便功能
 * @author liuricheng
 * 
 */	
class Utils{
   
	/**
	 * 检查分类是否已经存在
	 *
	 * @param   string      $cat_name       分类名称
	 * @param   integer     $parent_cat     上级分类
	 * @param   integer     $exclude        排除的分类ID
	 *
	 * @return  boolean
	 */
	public static function cat_exists($cat_name, $parent_cat, $exclude = 0){
		$GoodsCatModel	=	M('Category');
	    $sql 			= 	"SELECT COUNT(*) count FROM  ybr_category  "
	    					."WHERE parent_id = '$parent_cat' AND cat_name = '$cat_name' AND cat_id<>'$exclude'";
	    //echo $sql;
	    $datas			=	$GoodsCatModel->query($sql);
	    return ($datas[0]['count']) > 0 ? true : false;
	}

	/**
	 * 截取UTF-8编码下字符串的函数
	 *
	 * @param   string      $str        被截取的字符串
	 * @param   int         $length     截取的长度
	 * @param   bool        $append     是否附加省略号
	 *
	 * @return  string
	 */
	public  static function sub_str($str, $length = 0, $append = true){
	    $str = trim($str);
	    $strlength = strlen($str);	
	    if ($length == 0 || $length >= $strlength){
	        return $str;
	    }
	    elseif ($length < 0){
	        $length = $strlength + $length;
	        if ($length < 0){
	            $length = $strlength;
	        }
	    }	
	    if (function_exists('mb_substr')){
	        $newstr = mb_substr($str, 0, $length, EC_CHARSET);
	    }
	    elseif (function_exists('iconv_substr')){
	        $newstr = iconv_substr($str, 0, $length, EC_CHARSET);
	    }
	    else{
	        //$newstr = trim_right(substr($str, 0, $length));
	        $newstr = substr($str, 0, $length);
	    }	
	    if ($append && $str != $newstr){
	        $newstr .= '...';
	    }	
	    return $newstr;
	}
	
	// 格式化数组,生成IN语句
	public static  function create_in_sql($values,$field_name = ''){
		if (empty($values)){
	        return $field_name . " IN ('') ";
	    }
	    else{
	    	$item_list_tmp 	=	'';
	    	$keys			=	array_keys($values[0]); // 获取数组key键值	    		    	
	    	foreach($values as $item){	    		
	    		if(!empty($item) && !empty($keys)){
	    			$key			=	$keys[0];	
	    			$item_list_tmp 	.= 	( $item_list_tmp !='') ? ",'{$item[$key]}'" : "'{$item[$key]}'";
	    		}
	    	}
	    }
        if (empty($item_list_tmp)){
            return $field_name . " IN ('') ";
        }
        else{
            return $field_name . ' IN (' . $item_list_tmp . ') ';
        }	    
	} 
	
	// 判断是否存在相同的属性
	public static function attributeExists($attr_name, $value, $con){
		$AttributeModel		=	M('Attribute');
		$result				=	$AttributeModel->field(" count(*) count ")->where(" `{$attr_name}` = '{$value}' and {$con}")->find();
		return $result['count'];
	}
	
	/**
	 * 创建像这样的查询: "IN('a','b')";
	 *
	 * @access   public
	 * @param    mix      $item_list      列表数组或字符串
	 * @param    string   $field_name     字段名称
	 *
	 * @return   void
	 */
	public static function db_create_in($item_list, $field_name = ''){
	    if (empty($item_list)){
	        return $field_name . " IN ('') ";
	    }
	    else{
	        if (!is_array($item_list)){
	            $item_list 		= 	explode(',', $item_list);
	        }
	        $item_list 			= 	array_unique($item_list);
	        $item_list_tmp = '';
	        foreach ($item_list AS $item){
	            if ($item !== ''){
	                $item_list_tmp .= $item_list_tmp ? ",'$item'" : "'$item'";
	            }
	        }
	        if (empty($item_list_tmp)){
	            return $field_name . " IN ('') ";
	        }
	        else{
	            return $field_name . ' IN (' . $item_list_tmp . ') ';
	        }
	    }
	}
	
	/**
	 * 对 MYSQL LIKE 的内容进行转义
	 * @access      public
	 * @param       string      string  内容
	 * @return      string
	 * 
	 */
	public static function mysql_like_quote($str){
	    return strtr($str, array("\\\\" => "\\\\\\\\", '_' => '\_', '%' => '\%', "\'" => "\\\\\'"));
	}
	
	
	/**
	 * 检查图片的类型
	 * @param   string  $img_type   图片类型
	 * @return  bool
	 */
    public static function check_img_type($img_type){
        return $img_type == 'image/pjpeg' ||
               $img_type == 'image/x-png' ||
               $img_type == 'image/png'   ||
               $img_type == 'image/gif'   ||
               $img_type == 'image/jpeg';
    }
	
	/**
	 *  将一个用户自定义时区的日期转为GMT时间戳
	 *
	 * @access  public
	 * @param   string      $str
	 *
	 * @return  integer
	 */
	function local_strtotime($str){
	    return strtotime($str);
	}
    
	/**
	 * 获得当前格林威治时间的时间戳
	 *
	 * @return  integer
	 */
	public static function gmtime(){
	    return time();
	}
	
	/**
	 * 取得推荐类型列表
	 * @return  array   推荐类型列表
	 */
	public static function get_intro_list(){
	    return array(
	        'is_best'    	=>'精品',
	        'is_new'     	=>'新品',
	        'is_hot'    	=>'热销',
	        'is_promote' 	=>'特价',
	        'all_type' 		=>'全部推荐',
	    );
	}
	
		
	/**
	 *  生成一个用户自定义时区日期的GMT时间戳
	 *
	 * @access  public
	 * @param   int     $hour
	 * @param   int     $minute
	 * @param   int     $second
	 * @param   int     $month
	 * @param   int     $day
	 * @param   int     $year
	 *
	 * @return void
	 */
	function local_mktime($hour = NULL , $minute= NULL, $second = NULL,  $month = NULL,  $day = NULL,  $year = NULL){
	    return mktime($hour, $minute, $second, $month, $day, $year);
	}

	/**
	 * 获得商品列表sql语句
	 *
	 * @access  public
	 * @params  integer $isdelete
	 * @params  integer $real_goods
	 * @params  integer $conditions
	 * @return  array
	 */
	public static function sql_goods_list($is_delete, $real_goods=1, $conditions = ''){
	    /* 过滤条件 */
        $day 						= 	getdate();
        $today 						= 	Utils::local_mktime(23, 59, 59, $day['mon'], $day['mday'], $day['year']);
        $filter['cat_id']           = 	empty($_REQUEST['cat_id']) ? 0 : intval($_REQUEST['cat_id']);
        $filter['intro_type']       = 	empty($_REQUEST['intro_type']) ? '' : trim($_REQUEST['intro_type']);
        $filter['is_promote']       = 	empty($_REQUEST['is_promote']) ? 0 : intval($_REQUEST['is_promote']);
        $filter['stock_warning']    = 	empty($_REQUEST['stock_warning']) ? 0 : intval($_REQUEST['stock_warning']);
        $filter['brand_id']         = 	empty($_REQUEST['brand_id']) ? 0 : intval($_REQUEST['brand_id']);
        $filter['keyword']          = 	empty($_REQUEST['keyword']) ? '' : trim($_REQUEST['keyword']);
        $filter['suppliers_id'] 	= 	isset($_REQUEST['suppliers_id']) ? (empty($_REQUEST['suppliers_id']) ? '' : trim($_REQUEST['suppliers_id'])) : '';
        $filter['is_on_sale'] 		= 	isset($_REQUEST['is_on_sale']) ? ((empty($_REQUEST['is_on_sale']) && $_REQUEST['is_on_sale'] === 0) ? '' : trim($_REQUEST['is_on_sale'])) : '';
		$filter['sort_by']    		= 	empty($_REQUEST['sort_by']) ? 'goods_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order']       = 	empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);
        $filter['extension_code']   = 	empty($_REQUEST['extension_code']) ? '' : trim($_REQUEST['extension_code']);
        $filter['is_delete']        = 	$is_delete;
        $filter['real_goods']       = 	$real_goods;
        
        $where 						= 	$filter['cat_id'] > 0 ? " AND " . get_children($filter['cat_id']) : '';

        /* 推荐类型 */
        switch ($filter['intro_type']){
            case 'is_best':
                $where .= " AND is_best=1";
                break;
            case 'is_hot':
                $where .= ' AND is_hot=1';
                break;
            case 'is_new':
                $where .= ' AND is_new=1';
                break;
            case 'is_promote':
                $where .= " AND is_promote = 1 AND promote_price > 0 AND promote_start_date <= '$today' AND promote_end_date >= '$today'";
                break;
            case 'all_type';
                $where .= " AND (is_best=1 OR is_hot=1 OR is_new=1 OR (is_promote = 1 AND promote_price > 0 AND promote_start_date <= '" . $today . "' AND promote_end_date >= '" . $today . "'))";
        }

        /* 库存警告 */
        if ($filter['stock_warning']){
            $where .= ' AND goods_number <= warn_number ';
        }

        /* 品牌 */
        if ($filter['brand_id']){
            $where .= " AND brand_id='$filter[brand_id]'";
        }

        /* 扩展 */
        if ($filter['extension_code']){
            $where .= " AND extension_code='$filter[extension_code]'";
        }

        /* 关键字 */
        if (!empty($filter['keyword'])){
            $where .= " AND (goods_sn LIKE '%" . $filter['keyword'] . "%' OR goods_name LIKE '%" . $filter['keyword'] . "%')";
        }

        if ($real_goods > -1){
            $where .= " AND is_real='$real_goods'";
        }

        /* 上架 */
        if ($filter['is_on_sale'] !== ''){
            $where .= " AND (is_on_sale = '" . $filter['is_on_sale'] . "')";
        }

        /* 供货商 */
        if (!empty($filter['suppliers_id'])){
            $where .= " AND (suppliers_id = '" . $filter['suppliers_id'] . "')";
        }

        $where 	.= $conditions;

        $sql 	= 	"SELECT goods_id, goods_name, goods_type, goods_sn, shop_price, is_on_sale, is_best, is_new, is_hot, sort_order, goods_number, integral,extension_code, " .
                    " (promote_price > 0 AND promote_start_date <= '$today' AND promote_end_date >= '$today') AS is_promote ".
                    " FROM ybr_goods  AS g WHERE is_delete='$is_delete' $where" .
                    " ORDER BY $filter[sort_by] $filter[sort_order] ";
        //$filter['keyword'] = stripslashes($filter['keyword']);
	    return $sql;
	}
	
    /**
     * 判断表中某字段是否重复，若重复则中止程序，并给出错误信息
     *
     * @access  public
     * @param   string  $col    字段名
     * @param   string  $name   字段值
     * @param   integer $id
     *
     * @return void
     */
    public static function is_only($table,$col, $name, $id = 0, $where=''){
        $sql = 'SELECT COUNT(*) count FROM ' . "ybr_{$table}" . " WHERE $col = '$name'";
        $sql .= empty($id) ? '' : ' AND ' . $this->id . " <> '$id'";
        $sql .= empty($where) ? '' : ' AND ' .$where;        
        $result	=	M()->query($sql);
        return ($result[0]['count'] == 0);
    }
	
    /**
	 * 获得指定文章分类下所有底层分类的ID
	 *
	 * @access  public
	 * @param   integer     $cat        指定的分类ID
	 *
	 */
	function get_article_children ($cat = 0){
	    return Utils::db_create_in(array_unique(array_merge(array($cat), array_keys(Utils::article_cat_list($cat, 0, false)))), 'cat_id');
	}
		
	/**
	 * 获得指定分类下的子分类的数组
	 *
	 * @access  public
	 * @param   int     $cat_id     分类的ID
	 * @param   int     $selected   当前选中分类的ID
	 * @param   boolean $re_type    返回的类型: 值为真时返回下拉列表,否则返回数组
	 * @param   int     $level      限定返回的级数。为0时返回所有级数
	 * @return  mix
	 * 
	 */
	public static function article_cat_list($cat_id = 0, $selected = 0, $re_type = true, $level = 0){
	    //static $res = NULL;	
	    //if ($res === NULL){
	        //$data = read_static_cache('art_cat_pid_releate');
	        if ($data === false){
	            $sql 	= 	"SELECT c.*, COUNT(s.cat_id) AS has_children, COUNT(a.article_id) AS aricle_num ". ' FROM ' . 'article_cat' . " AS c".
	    	           		" LEFT JOIN " . 'article_cat' . " AS s ON s.parent_id=c.cat_id".
			              	" LEFT JOIN " . 'article' . " AS a ON a.cat_id=c.cat_id".
	        		       	" GROUP BY c.cat_id ".
	               			" ORDER BY parent_id, sort_order ASC";
	            $res	=	M()->query($sql);
	        }
	        else{
	            $res = $data;
	        }
	    //}
	
	    if (empty($res) == true){
	        return $re_type ? '' : array();
	    }
	
	    $options 	= 	article_cat_options($cat_id, $res); // 获得指定分类下的子分类的数组
	
	    /* 截取到指定的缩减级别 */
	    if ($level > 0){
	        if ($cat_id == 0){
	            $end_level = $level;
	        }
	        else{
	            $first_item = reset($options); // 获取第一个元素
	            $end_level  = $first_item['level'] + $level;
	        }
	
	        /* 保留level小于end_level的部分 */
	        foreach ($options AS $key => $val){
	            if ($val['level'] >= $end_level){
	                unset($options[$key]);
	            }
	        }
	    }
	
	    $pre_key = 0;
	    foreach ($options AS $key => $value){
	        $options[$key]['has_children'] = 1;
	        if ($pre_key > 0){
	            if ($options[$pre_key]['cat_id'] == $options[$key]['parent_id']){
	                $options[$pre_key]['has_children'] = 1;
	            }
	        }
	        $pre_key = $key;
	    }
	
	    if ($re_type == true){
	        $select = '';
	        foreach ($options AS $var){
	            $select .= '<option value="' . $var['cat_id'] . '" ';
	            $select .= ' cat_type="' . $var['cat_type'] . '" ';
	            $select .= ($selected == $var['cat_id']) ? "selected='ture'" : '';
	            $select .= '>';
	            if ($var['level'] > 0){
	                $select .= str_repeat('&nbsp;', $var['level'] * 4);
	            }
	            $select .= htmlspecialchars(addslashes($var['cat_name'])) . '</option>';
	        }
	
	        return $select;
	    }
	    else{
	        foreach ($options AS $key => $value){
	            //$options[$key]['url'] = build_uri('article_cat', array('acid' => $value['cat_id']), $value['cat_name']);
	        }
	        return $options;
	    }
	}
	
	
	
	/**
	 * 过滤和排序所有文章分类，返回一个带有缩进级别的数组
	 *
	 * @access  private
	 * @param   int     $cat_id     上级分类ID
	 * @param   array   $arr        含有所有分类的数组
	 * @param   int     $level      级别
	 * @return  void
	 */
	function article_cat_options($spec_cat_id, $arr)
	{
	    static $cat_options = array();
	
	    if (isset($cat_options[$spec_cat_id]))
	    {
	        return $cat_options[$spec_cat_id];
	    }
	
	    if (!isset($cat_options[0]))
	    {
	        $level = $last_cat_id = 0;
	        $options = $cat_id_array = $level_array = array();
	        while (!empty($arr))
	        {
	            foreach ($arr AS $key => $value)
	            {
	                $cat_id = $value['cat_id'];
	                if ($level == 0 && $last_cat_id == 0)
	                {
	                    if ($value['parent_id'] > 0)
	                    {
	                        break;
	                    }
	
	                    $options[$cat_id]          = $value;
	                    $options[$cat_id]['level'] = $level;
	                    $options[$cat_id]['id']    = $cat_id;
	                    $options[$cat_id]['name']  = $value['cat_name'];
	                    unset($arr[$key]);
	
	                    if ($value['has_children'] == 0)
	                    {
	                        continue;
	                    }
	                    $last_cat_id  = $cat_id;
	                    $cat_id_array = array($cat_id);
	                    $level_array[$last_cat_id] = ++$level;
	                    continue;
	                }
	
	                if ($value['parent_id'] == $last_cat_id)
	                {
	                    $options[$cat_id]          = $value;
	                    $options[$cat_id]['level'] = $level;
	                    $options[$cat_id]['id']    = $cat_id;
	                    $options[$cat_id]['name']  = $value['cat_name'];
	                    unset($arr[$key]);
	
	                    if ($value['has_children'] > 0)
	                    {
	                        if (end($cat_id_array) != $last_cat_id)
	                        {
	                            $cat_id_array[] = $last_cat_id;
	                        }
	                        $last_cat_id    = $cat_id;
	                        $cat_id_array[] = $cat_id;
	                        $level_array[$last_cat_id] = ++$level;
	                    }
	                }
	                elseif ($value['parent_id'] > $last_cat_id)
	                {
	                    break;
	                }
	            }
	
	            $count = count($cat_id_array);
	            if ($count > 1)
	            {
	                $last_cat_id = array_pop($cat_id_array);
	            }
	            elseif ($count == 1)
	            {
	                if ($last_cat_id != end($cat_id_array))
	                {
	                    $last_cat_id = end($cat_id_array);
	                }
	                else
	                {
	                    $level = 0;
	                    $last_cat_id = 0;
	                    $cat_id_array = array();
	                    continue;
	                }
	            }
	
	            if ($last_cat_id && isset($level_array[$last_cat_id]))
	            {
	                $level = $level_array[$last_cat_id];
	            }
	            else
	            {
	                $level = 0;
	            }
	        }
	        $cat_options[0] = $options;
	    }
	    else
	    {
	        $options = $cat_options[0];
	    }
	
	    if (!$spec_cat_id)
	    {
	        return $options;
	    }
	    else
	    {
	        if (empty($options[$spec_cat_id]))
	        {
	            return array();
	        }
	
	        $spec_cat_id_level = $options[$spec_cat_id]['level'];
	
	        foreach ($options AS $key => $value)
	        {
	            if ($key != $spec_cat_id)
	            {
	                unset($options[$key]);
	            }
	            else
	            {
	                break;
	            }
	        }
	
	        $spec_cat_id_array = array();
	        foreach ($options AS $key => $value)
	        {
	            if (($spec_cat_id_level == $value['level'] && $value['cat_id'] != $spec_cat_id) ||
	                ($spec_cat_id_level > $value['level']))
	            {
	                break;
	            }
	            else
	            {
	                $spec_cat_id_array[$key] = $value;
	            }
	        }
	        $cat_options[$spec_cat_id] = $spec_cat_id_array;
	
	        return $spec_cat_id_array;
	    }
	}
	


	
	


	
}
?>